//
//  IAPModels.swift
//  Combine-IAP-Demo
//
//  Created by garvin on 2025/1/7.
//

import Foundation
import StoreKit

// MARK: - 购买状态枚举
/// 表示内购过程中的不同状态
public enum PurchaseState {
    /// 购买中
    case purchasing
    /// 购买成功
    case purchased(transaction: SKPaymentTransaction)
    /// 购买失败
    case failed(error: Error)
    /// 购买被延期（如家庭共享等待批准）
    case deferred
    
    /// 状态的中文描述
    public var localizedDescription: String {
        switch self {
        case .purchasing:
            return "正在购买..."
        case .purchased(_):
            return "购买成功"
        case .failed(let error):
            return "购买失败: \(error.localizedDescription)"
        case .deferred:
            return "购买等待批准"
        }
    }
}

// MARK: - 内购错误枚举
/// 统一的内购错误类型
public enum IAPError: Error {
    /// 产品未找到
    case productNotFound
    /// 购买失败（包含原始错误）
    case purchaseFailed(underlying: Error)
    /// 网络错误
    case networkError
    /// 用户取消购买
    case userCancelled
    /// 无法连接到App Store
    case storeUnavailable
    /// 收据验证失败
    case receiptValidationFailed
    /// 产品请求失败
    case productRequestFailed(underlying: Error)
    
    /// 错误的中文描述
    public var localizedDescription: String {
        switch self {
        case .productNotFound:
            return "未找到指定产品"
        case .purchaseFailed(let error):
            return "购买失败: \(error.localizedDescription)"
        case .networkError:
            return "网络连接错误"
        case .userCancelled:
            return "用户取消了购买"
        case .storeUnavailable:
            return "App Store 暂时不可用"
        case .receiptValidationFailed:
            return "收据验证失败"
        case .productRequestFailed(let error):
            return "产品信息获取失败: \(error.localizedDescription)"
        }
    }
    
    /// 错误代码，便于日志记录和分析
    public var errorCode: Int {
        switch self {
        case .productNotFound: return 1001
        case .purchaseFailed(_): return 1002
        case .networkError: return 1003
        case .userCancelled: return 1004
        case .storeUnavailable: return 1005
        case .receiptValidationFailed: return 1006
        case .productRequestFailed(_): return 1007
        }
    }
}

// MARK: - 扩展支持
extension IAPError: LocalizedError {
    public var errorDescription: String? {
        return localizedDescription
    }
} 